package com.mk.springbootvuedemo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.springbootvuedemo.config.Result;
import com.mk.springbootvuedemo.entity.Book;
import com.mk.springbootvuedemo.mapper.BookMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

//定义返回JSON对象的controller
@RestController
//接口统一的路由
@RequestMapping("/book")
public class BookController {
    @Resource
    BookMapper BookMapper;

//    定义post接口,post是新增
    @PostMapping("/insert")
    //    @RequestBody把JOSN对象转换成JAVA对象
    public Result<?> save(@RequestBody Book Book){
        BookMapper.insert(Book);
        return Result.success();
    }

    //Delete是删除
    @DeleteMapping("/{id}")//占位符的方式要通过@PathhVariable获取
    public Result<?> update(@PathVariable Long id){
        BookMapper.deleteById(id);
        return Result.success();
    }
    //Put是更新
    @PutMapping("/update")
    public Result<?> update(@RequestBody Book Book){
        BookMapper.updateById(Book);
        return Result.success();
    }
@PostMapping("/deleteBatch")
public Result<?> deleteBatch(@RequestBody List<Integer> ids){
        BookMapper.deleteBatchIds(ids);
        return Result.success();
}
    //Get是查询
    @GetMapping("/search")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Book> wrapper=Wrappers.<Book>lambdaQuery();
//        避免nickName没有数据时查不出来
        if(StrUtil.isNotBlank(search)){
            wrapper.like(Book::getName,search);
        }
        Page<Book> BookPage= BookMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(BookPage);
    }
}
